function aSpeedQuest_SlashCommandHandler(msg)
	local args = {strsplit(" ", msg)};
	if (args[1] == "" or args[1] == "toggle") then
		ASQDB.State = not ASQDB.State;
		aSpeedQuest_DoRegs();
		if ASQDB.State then
			print("aSpeedQuest is now online!");
		else
			print("aSpeedQuest is now offline!");
		end
	elseif (args[1] == "scan") then
		local spec = tonumber(args[2]);
		aSpeedQuest_Scan(spec);
		print("Scanned current gear for spec", spec);
	elseif (args[1] == "autopick") then
		ASQDB.Autopick = not ASQDB.Autopick;
		if ASQDB.Autopick then
			print("Picking rewards for you");
		else
			print("No longer picking rewards for you");
		end
	elseif (args[1] == "liststats") then
		for key, value in pairs(ASQ_StatStrings) do
			print(key, _G[value]);			
		end
	elseif (args[1] == "setw") then
		local spec = tonumber(args[2]);
		local stat = ASQ_StatStrings[args[3] ];
		local value = tonumber(args[4]);
		if (stat) then
			if(ASQDB.Weights[spec]) then
				ASQDB.Weights[spec][stat] = value;
				print("Weight for", _G[stat], "set to", value, "for spec", spec);
			else
				print("Couldn't find spec", spec);
			end
		else
			print("Couldn't find stat", args[3]);
		end
	elseif (args[1] == "show") then
		local spec = tonumber(args[2]);
		if(ASQDB.Weights[spec]) then
			print("--Weights for spec", spec..":--");
			for stat, weight in pairs(ASQDB.Weights[spec]) do
				print(_G[stat]..":", weight);
			end
			local types = "Types: ";
			for key, value in pairs(ASQDB.ItemTypes[spec]) do
				if value then
					types = types..key..", ";
				end
			end
			print(types);
		else
			print("Couldn't find spec", spec);
		end
	elseif (args[1] == "addspec") then
		local specNum = #ASQDB.Weights + 1
		ASQDB.Weights[specNum] = {};
		ASQDB.ItemTypes[specNum] = {};
		ASQDB.Scores[specNum] = {};
		print("Added spec #"..specNum);
	elseif (args[1] == "delspec") then
		local specNum = tonumber(args[2]);
		table.remove(ASQDB.Weights, specNum);
		table.remove(ASQDB.ItemTypes, specNum);
		table.remove(ASQDB.Scores, specNum);
		print("Removed spec #"..specNum);
	elseif (args[1] == "addprio") then
		local itemname = args[2];
		for i = 3, #args do
			itemname = itemname.." " ..args[i];
		end
		ASQDB.PrioItems[itemname] = true;
		print("Added", itemname, "to prio items");
	elseif (args[1] == "delprio") then
		local itemname = args[2];
		for i = 3, #args do
			itemname = itemname.." " ..args[i];
		end
		--ASQDB.PrioItems[itemname] = nil;
		ASQDB.PrioItems = aSpeedQuest_RemoveKey(ASQDB.PrioItems, itemname);
		print("Removed", itemname, "from prio items");
	elseif (args[1] == "listprio") then
		local prios = "Prio Items: ";
		for key, value in pairs(ASQDB.PrioItems) do
			if value then
				prios = prios..key..", ";
			end
		end
		print(prios);
	elseif (args[1] == "addtype") then
		local spec = tonumber(args[2]);
		local itemtype = args[3];
		for i = 4, #args do
			itemtype = itemtype.." " ..args[i];
		end
		if(ASQDB.ItemTypes[spec]) then
			ASQDB.ItemTypes[spec][itemtype] = true;
		end
		print("Added", itemtype, "to spec", spec);
	elseif (args[1] == "deltype") then
		local spec = tonumber(args[2]);
		local itemtype = args[3];
		for i = 4, #args do
			itemtype = itemtype.." " ..args[i];
		end
		if(ASQDB.ItemTypes[spec]) then
			ASQDB.ItemTypes[spec][itemtype] = false;
		end
		print("Removed", itemtype, "from spec", spec);
	elseif (args[1] == "listtypes") then
		print("Weapon: One-Handed Axes, Two-Handed Axes, Bows, Guns, One-Handed Maces, Two-Handed Maces, Polearms, One-Handed Swords, Two-Handed Swords, Staves, Fist Weapons, Miscellaneous, Daggers, Thrown, Crossbows, Wands, Fishing Poles");
		print("Armor: Miscellaneous, Cloth, Leather, Mail, Plate, Shields, Relic");
	elseif (args[1] == "cleanq") then
		aSpeedQuest_CheckQuestItems();
		--QueryQuestsCompleted();
	elseif (args[1] == "reset") then
		aSpeedQuest_Init();
		aSpeedQuest_DoRegs();
		print("Reset everything to default");
	elseif (args[1] == "share") then
		aSpeedQuest_StartShare();
	elseif (args[1] == "macro") then	
		if(GetMacroIndexByName(ASQ_MacroName) == 0) then
			local nAccMac, nCharMac = GetNumMacros();
			if nAccMac < 36 then
				CreateMacro(ASQ_MacroName, "INV_Misc_QuestionMark", nil);
			elseif nCharMax < 18 then
				CreateMacro(ASQ_MacroName, "INV_Misc_QuestionMark", nil, 1);			
			end
		end
	elseif (args[1] == "?" or args[1] == "help") then
		print("--Commands: (/asq [command] [args])--");
		print("toggle - Toggles ASQ on/off");
		print("share - Attempts to share all your quests");
		print("autopick - Toggles automatic quest rewards");
		print("macro - Creates automatic quest macro");
		print("reset - Resets EVERYTHING to defaults");
		print("?pick - Shows autopick related commands");
	elseif (args[1] == "?pick") then
		print("--Autopick Related Commands: (/asq [command] [args])--");
		print("autopick - Toggles automatic quest rewards");
		print("addprio [name] - Adds an item to priority list");
		print("delprio [name] - Removes an item from priority list");
		print("listprio - Lists prioritized items");
		print("scan [spec] - Scans your current gear for [spec]");
		print("show [spec] - Shows weights and types for [spec]");
		print("addspec - Adds a new, empty spec to the end of the list (lowest prio)");
		print("delspec [spec] - Removes [spec]");
		print("setw [spec] [stat] [value] - Sets weight for a spec/stat to value");
		print("liststats - Lists stat shortcuts for use with setw");
		print("addtype [spec] [type] - Adds a weapon/armor type to [spec]");
		print("deltype [spec] [type] - Removes a weapon/armor type from [spec]");
		print("listtypes - Lists available weapon/armor types");
		print("cleanq - Cleans up quest list to minimize memory usage");
	end
end

function aSpeedQuest_DoRegs()
	if ASQDB.State then
		ASQ:RegisterEvent("PARTY_MEMBERS_CHANGED");
		ASQ:RegisterEvent("QUEST_ACCEPTED");
		ASQ:RegisterEvent("QUEST_COMPLETE");
		ASQ:RegisterEvent("QUEST_PROGRESS");
		ASQ:RegisterEvent("GOSSIP_SHOW");
		ASQ:RegisterEvent("QUEST_GREETING");
		ASQ:RegisterEvent("QUEST_DETAIL");
		ASQ:RegisterEvent("QUEST_QUERY_COMPLETE");
		ASQ:RegisterEvent("QUEST_ACCEPT_CONFIRM");
		--Mass share related
		ASQ:RegisterEvent("CHAT_MSG_SYSTEM");	
	else
		ASQ:UnregisterEvent("PARTY_MEMBERS_CHANGED");
		ASQ:UnregisterEvent("QUEST_ACCEPTED");
		ASQ:UnregisterEvent("QUEST_COMPLETE");
		ASQ:UnregisterEvent("QUEST_PROGRESS");
		ASQ:UnregisterEvent("GOSSIP_SHOW");
		ASQ:UnregisterEvent("QUEST_GREETING");
		ASQ:UnregisterEvent("QUEST_DETAIL");
		ASQ:UnregisterEvent("QUEST_QUERY_COMPLETE");
		ASQ:UnregisterEvent("QUEST_ACCEPT_CONFIRM");
		--Mass share related
		ASQ:UnregisterEvent("CHAT_MSG_SYSTEM");
	end
end

function aSpeedQuest_OnLoad(self)
	SlashCmdList["ASPEEDQUEST"] = aSpeedQuest_SlashCommandHandler;
	SLASH_ASPEEDQUEST1 = "/asq";
	--ASQ_Prefix = "ASQWITHSALT";
	ASQ = self;
	ASQ:RegisterEvent("ADDON_LOADED");
	ASQ_CurrentVer = 0; --Changing this removes all old savedvars
	ASQ_GossipCount = 1;
	ASQ_StatStrings = {	["agi"] = "ITEM_MOD_AGILITY_SHORT",
						["int"] = "ITEM_MOD_INTELLECT_SHORT",
						["str"] = "ITEM_MOD_STRENGTH_SHORT",
						["sta"] = "ITEM_MOD_STAMINA_SHORT",
						["spi"] = "ITEM_MOD_SPIRIT_SHORT",
						["dps"] = "ITEM_MOD_DAMAGE_PER_SECOND_SHORT",
						["sp"] = "ITEM_MOD_SPELL_POWER_SHORT",
						["dod"] = "ITEM_MOD_DODGE_RATING_SHORT",
						["par"] = "ITEM_MOD_PARRY_RATING_SHORT",
						["mas"] = "ITEM_MOD_MASTERY_RATING_SHORT",
						["cri"] = "ITEM_MOD_CRIT_RATING_SHORT",
						["has"] = "ITEM_MOD_HASTE_RATING_SHORT",
						["hit"] = "ITEM_MOD_HIT_RATING_SHORT",
						["exp"] = "ITEM_MOD_EXPERTISE_RATING_SHORT",
						["ap"] = "ITEM_MOD_ATTACK_POWER_SHORT"};
	ASQ_ScanSlots = {"HeadSlot", "NeckSlot", "ShoulderSlot", "BackSlot",
					 "ChestSlot", "WristSlot", "HandsSlot", "WaistSlot",
					 "LegsSlot", "FeetSlot", "Finger0Slot", "Finger1Slot",
					 "MainHandSlot", "SecondaryHandSlot", };
	ASQ_EquipSlots = {["INVTYPE_2HWEAPON"] = {"TwoHandSlot"},					  
					  ["INVTYPE_CHEST"] = {"ChestSlot"},
					  ["INVTYPE_CLOAK"] = {"BackSlot"},
					  ["INVTYPE_FEET"] = {"FeetSlot"},
					  ["INVTYPE_FINGER"] = {"Finger0Slot", "Finger1Slot"},
					  ["INVTYPE_HAND"] = {"HandsSlot"},
					  ["INVTYPE_HEAD"] = {"HeadSlot"},
					  ["INVTYPE_HOLDABLE"] = {"SecondaryHandSlot"},
					  ["INVTYPE_LEGS"] = {"LegsSlot"},
					  ["INVTYPE_NECK"] = {"NeckSlot"},
					  ["INVTYPE_RANGED"] = {"RangedSlot"},
					  ["INVTYPE_RANGEDRIGHT"] = {"RangedSlot"},
					  ["INVTYPE_ROBE"] = {"ChestSlot"},
					  ["INVTYPE_SHIELD"] = {"SecondaryHandSlot"},
					  ["INVTYPE_SHOULDER"] = {"ShoulderSlot"},
					  ["INVTYPE_THROWN"] = {"RangedSlot"},
					  ["INVTYPE_WAIST"] = {"WaistSlot"},
					  ["INVTYPE_WEAPON"] = {"MainHandSlot", "SecondaryHandSlot"},
					  ["INVTYPE_WEAPONMAINHAND"] = {"MainHandSlot"},
					  ["INVTYPE_WEAPONMAINHAND_PET"] = {"MainHandSlot"},
					  ["INVTYPE_WEAPONOFFHAND"] = {"SecondaryHandSlot"},
					  ["INVTYPE_WRIST"] = {"WristSlot"}, };
	ASQ_GenericSlots = {["INVTYPE_CLOAK"] = true,
						["INVTYPE_FINGER"] = true,
						["INVTYPE_NECK"] = true, };
	ASQ_MacroName = "ASQ macro";
	--[[
	ASQ_QuestMacros = {	[30084] = "/use Flame of Zhu's Watch",
					[30090] = "/use Ken-Ken's Mask",
					[30460] = "/use Dit Da Jow",
					[30690] = "/use Blinding Rage Trap",
					[30795] = "/use The Tongue of Ba-Shon",
					[30773] = "/use Ban's Explosives",
					[30778] = "/use Shado-Pan Torch",
					[30888] = "/use Shado-Pan Flare",
					[30892] = "/use Citron-Infused Bandages",
					[31032] = "/use Wu Kao Torch",
					[30923] = "/use Gunpowder Casks", };
					--]]--
	if GetNumPartyMembers then
		GetNumGroupMembers = GetNumPartyMembers;
	end
	ASQ_NoDialog = {["Master Bruised Paw"] = true,
					["Daggle Bombstrider"] = true,
					["Forward Commander Kingston"] = true,
					["Brother Oilyak"] = true,};
	--Hook questlog reward on click function
	--ASQ_oldFunc = QuestInfoItem1:GetScript("OnClick"); -- Old hooking method, unnecessary?
	for i = 1, MAX_NUM_ITEMS do
        _G["QuestInfoItem"..i]:HookScript("OnClick", aSpeedQuest_LogItemOnClick);
    end
	
	print("SPEEDQUESTING IS LOADED!!!1");
end

function aSpeedQuest_RemoveKey(tablee, rKey)
	local temp = {};
	for key, value in pairs(tablee) do
		if(key ~= rKey) then
			temp[key] = value;
		end
	end
	return temp;
end

function aSpeedQuest_LogItemOnClick(self, button, down)
	if ( not IsModifiedClick() and self.objectType == "item" and QuestInfoFrame.questLog) then
		local questID = select(9, GetQuestLogTitle(GetQuestLogSelection()));
		local itemName = GetQuestLogChoiceInfo(self:GetID());
		if ASQDB.QuestItems[questID] then
			--ASQDB.PrioItems[ASQDB.QuestItems[questID]] = nil;
			ASQDB.PrioItems = aSpeedQuest_RemoveKey(ASQDB.PrioItems, ASQDB.QuestItems[questID]);
			print("Removed", ASQDB.QuestItems[questID], "from prio list");
		end
		ASQDB.PrioItems[itemName] = true;
		ASQDB.QuestItems[questID] = itemName;
		print("Added", itemName, "to prio list");
	end
	--return ASQ_oldFunc(self, button, down);
end

function aSpeedQuest_Scan(spec)
	for _, slot in ipairs(ASQ_ScanSlots) do
		local itemlink = GetInventoryItemLink("player", GetInventorySlotInfo(slot));
		local score = 0;
		if itemlink then
			local stats = GetItemStats(itemlink);
			local name, _, _, _, _, _, subclass, _, equipslot, _, _ = GetItemInfo(itemlink);
			score = aSpeedQuest_ItemScore(stats, subclass, spec, equipslot);
		end
		ASQDB.Scores[spec][slot] = score;
	end
end

function aSpeedQuest_Init()
	
	ASQDB = {};
	ASQDB.Ver = ASQ_CurrentVer;
	if(select(2,UnitClass("player")) == "ROGUE") then
		ASQDB.State = true;
		ASQDB.Autopick = true;
		ASQDB.PrioItems = {};
		ASQDB.QuestItems = {};
		
		--Statweight and related tables:
		ASQDB.Weights = {};
		ASQDB.ItemTypes = {};
		ASQDB.Scores = {};
		ASQDB.Weights[1] = {["ITEM_MOD_AGILITY_SHORT"]=30,
							["ITEM_MOD_DAMAGE_PER_SECOND_SHORT"]=20,
							["ITEM_MOD_CRIT_RATING_SHORT"]=15,
							["ITEM_MOD_HASTE_RATING_SHORT"]=15,
							["ITEM_MOD_MASTERY_RATING_SHORT"]=15,
							["ITEM_MOD_HIT_RATING_SHORT"]=20,
							["ITEM_MOD_EXPERTISE_RATING_SHORT"]=30,
							};
		ASQDB.ItemTypes[1] = {["One-Handed Maces"]=true,
							  ["One-Handed Axes"]=true,
							  ["One-Handed Swords"]=true,
							  ["Dagger"]=true,
							  ["Fist Weapons"]=true,
							  ["Leather"]=true,
							 };	
		ASQDB.Scores[1] = {};
	elseif(select(2,UnitClass("player")) == "MONK") then
		ASQDB.State = true;
		ASQDB.Autopick = true;
		ASQDB.PrioItems = {};
		ASQDB.QuestItems = {};
		
		--Statweight and related tables:
		ASQDB.Weights = {};
		ASQDB.ItemTypes = {};
		ASQDB.Scores = {};
		ASQDB.Weights[1] = {["ITEM_MOD_AGILITY_SHORT"]=30,
							["ITEM_MOD_DAMAGE_PER_SECOND_SHORT"]=20,
							["ITEM_MOD_CRIT_RATING_SHORT"]=15,
							["ITEM_MOD_HASTE_RATING_SHORT"]=15,
							["ITEM_MOD_MASTERY_RATING_SHORT"]=15,
							["ITEM_MOD_HIT_RATING_SHORT"]=20,
							["ITEM_MOD_EXPERTISE_RATING_SHORT"]=30,
							};
		ASQDB.ItemTypes[1] = {["One-Handed Maces"]=true,
							  ["One-Handed Axes"]=true,
							  ["One-Handed Swords"]=true,
							  ["Fist Weapons"]=true,
							  ["Staves"]=true,
							  ["Polearms"]=true,
							  ["Leather"]=true,
							 };	
		ASQDB.Scores[1] = {};
		ASQDB.Weights[2] = {["ITEM_MOD_INTELLECT_SHORT"]=50,
							["ITEM_MOD_SPIRIT_SHORT"]=45,
							["ITEM_MOD_CRIT_RATING_SHORT"]=20,
							["ITEM_MOD_HASTE_RATING_SHORT"]=30,
							["ITEM_MOD_MASTERY_RATING_SHORT"]=27,
							["ITEM_MOD_SPELL_POWER_SHORT"]=35,
							};
		ASQDB.ItemTypes[2] = {["One-Handed Maces"]=true,
							  ["One-Handed Axes"]=true,
							  ["One-Handed Swords"]=true,
							  ["Fist Weapons"]=true,
							  ["Staves"]=true,
							  ["Polearms"]=true,
							  ["Leather"]=true,
							 };	
		ASQDB.Scores[2] = {};
		ASQDB.Weights[3] = {["ITEM_MOD_STAMINA_SHORT"]=30,
							["ITEM_MOD_DODGE_RATING_SHORT"]=30,
							["ITEM_MOD_MASTERY_RATING_SHORT"]=30,
							["ITEM_MOD_AGILITY_SHORT"]=15,
							};
		ASQDB.ItemTypes[3] = {["One-Handed Maces"]=true,
							  ["One-Handed Axes"]=true,
							  ["One-Handed Swords"]=true,
							  ["Fist Weapons"]=true,
							  ["Staves"]=true,
							  ["Polearms"]=true,
							  ["Leather"]=true,
							 };	
		ASQDB.Scores[3] = {};
		
	elseif(GetUnitName("player") == "Dezi") then
		ASQDB.State = true;
		ASQDB.Autopick = false;
		ASQDB.PrioItems = {};
		ASQDB.QuestItems = {};
		
		--Statweight and related tables:
		ASQDB.Weights = {};
		ASQDB.ItemTypes = {};
		ASQDB.Scores = {};
		ASQDB.Weights[1] = {["ITEM_MOD_AGILITY_SHORT"]=42,
							["ITEM_MOD_DAMAGE_PER_SECOND_SHORT"]=42,
							["ITEM_MOD_CRIT_RATING_SHORT"]=14,
							["ITEM_MOD_HASTE_RATING_SHORT"]=12,
							["ITEM_MOD_MASTERY_RATING_SHORT"]=19,
							["ITEM_MOD_HIT_RATING_SHORT"]=17,
							["ITEM_MOD_EXPERTISE_RATING_SHORT"]=14,
							["ITEM_MOD_ATTACK_POWER_SHORT"]=14
							};
		ASQDB.ItemTypes[1] = {["One-Handed Maces"]=true,
							  ["One-Handed Axes"]=true,
							  ["Fist Weapons"]=true,
							  ["Mail"]=true,
							  ["Relic"]=true
							 };	
		ASQDB.Scores[1] = {};
		ASQDB.Weights[2] = {["ITEM_MOD_INTELLECT_SHORT"]=50,
							["ITEM_MOD_SPIRIT_SHORT"]=45,
							["ITEM_MOD_CRIT_RATING_SHORT"]=20,
							["ITEM_MOD_HASTE_RATING_SHORT"]=30,
							["ITEM_MOD_MASTERY_RATING_SHORT"]=27,
							["ITEM_MOD_SPELL_POWER_SHORT"]=35,
							};
		ASQDB.ItemTypes[2] = {["One-Handed Maces"]=true,
							  ["One-Handed Axes"]=true,
							  ["Two-Handed Maces"]=true,
							  ["Staves"]=true,
							  ["Daggers"]=true,
							  ["Fist Weapons"]=true,
							  ["Mail"]=true,
							  ["Shields"]=true,
							  ["Miscellaneous"]=true,
							  ["Relic"]=true
							 };
		ASQDB.Scores[2] = {};
	elseif(GetUnitName("player") == "Mevia") then
		ASQDB.State = true;
		ASQDB.Autopick = true;
		ASQDB.PrioItems = {};
		ASQDB.QuestItems = {};
		
		--Statweight and related tables:
		ASQDB.Weights = {};
		ASQDB.ItemTypes = {};
		ASQDB.Scores = {};
		ASQDB.Weights[1] = {["ITEM_MOD_AGILITY_SHORT"]=68,
							["ITEM_MOD_STRENGTH_SHORT"]=26,
							["ITEM_MOD_DAMAGE_PER_SECOND_SHORT"]=100,
							["ITEM_MOD_CRIT_RATING_SHORT"]=25,
							["ITEM_MOD_HASTE_RATING_SHORT"]=24,
							["ITEM_MOD_MASTERY_RATING_SHORT"]=24,
							["ITEM_MOD_HIT_RATING_SHORT"]=22,
							["ITEM_MOD_EXPERTISE_RATING_SHORT"]=44,
							["ITEM_MOD_ATTACK_POWER_SHORT"]=25
							};
		ASQDB.ItemTypes[1] = {["Two-Handed Maces"]=true,
							  ["Staves"]=true,
							  ["Polearms"]=true,
							  ["Leather"]=true,
							  ["Relic"]=true
							 };	
		ASQDB.Scores[1] = {};
		ASQDB.Weights[2] = {["ITEM_MOD_INTELLECT_SHORT"]=50,
							["ITEM_MOD_SPIRIT_SHORT"]=45,
							["ITEM_MOD_CRIT_RATING_SHORT"]=20,
							["ITEM_MOD_HASTE_RATING_SHORT"]=30,
							["ITEM_MOD_MASTERY_RATING_SHORT"]=27,
							["ITEM_MOD_SPELL_POWER_SHORT"]=35,
							};
		ASQDB.ItemTypes[2] = {["One-Handed Maces"]=true,
							  ["Two-Handed Maces"]=true,
							  ["Staves"]=true,
							  ["Daggers"]=true,
							  ["Polearms"]=true,
							  ["Fist Weapons"]=true,
							  ["Leather"]=true,
							  ["Miscellaneous"]=true,
							  ["Relic"]=true
							 };
		ASQDB.Scores[2] = {};
	else --Default Settings
		ASQDB.State = false;
		ASQDB.Autopick = false;
		ASQDB.PrioItems = {};
		ASQDB.Weights = {};
		ASQDB.ItemTypes = {};
		ASQDB.Scores = {};
		ASQDB.QuestItems = {};
	end	
end

function aSpeedQuest_PickItem(itemlinks)
	local stats = {};
	local name = {};
	local subclass = {};
	local equipslot = {};
	local value = {};
	local _;
	local hastrinket = false;
	for i, itemlink in ipairs(itemlinks) do
		stats[i] = GetItemStats(itemlink);
		name[i], _, _, _, _, _, subclass[i], _, equipslot[i], _, value[i] = GetItemInfo(itemlink);
		if equipslot[i] == "INVTYPE_TRINKET" then
			hastrinket = true;
		end
		if ASQDB.PrioItems[ name[i] ] then
			return i;
		end
	end
	if not ASQDB.Autopick then
		return nil;
	end
	if hastrinket then
		print(">>Trinket detected, you have to choose!<<");
		return;
	end
	local bestScore = 0;
	local bestIndex;
	local bestSlot;
	local bestTotal;
	for spec, _ in ipairs(ASQDB.Weights) do
		for i, stats in ipairs(stats) do
			local compareto, slot = aSpeedQuest_CompareTo(equipslot[i], spec);
			local totalScore = aSpeedQuest_ItemScore(stats, subclass[i], spec, equipslot[i]);
			local score = totalScore - compareto;
			if score > bestScore then
				bestScore = score;
				bestIndex = i;
				bestSlot = slot;
				bestTotal = totalScore;
			end
		end
		if bestIndex then
			--if (ASQDB.Autopick) then
			aSpeedQuest_SetScore(bestSlot, bestTotal, spec);
			print("Picked up", name[bestIndex], "for spec", spec, "and slot", bestSlot);
			--end
			return bestIndex;
		end
	end
	for i, value in ipairs(value) do
		if value > bestScore then
			bestScore = value;
			bestIndex = i;
		end
	end
	return bestIndex;
end

function aSpeedQuest_SetScore(slot, score, spec)
	if slot == "TwoHandSlot" then
		ASQDB.Scores[spec]["MainHandSlot"] = score - ASQDB.Scores[spec]["OffHandSlot"];
	else
		ASQDB.Scores[spec][slot] = score;
	end
end

function aSpeedQuest_CompareTo(equipslot, spec)
	if equipslot == "INVTYPE_2HWEAPON" then
		return (ASQDB.Scores[spec]["MainHandSlot"] + ASQDB.Scores[spec]["SecondaryHandSlot"]), "MainHandSlot"
	elseif (ASQ_EquipSlots[equipslot]) then
		local lowestScore;
		local bestSlot;
		for _, slot in ipairs(ASQ_EquipSlots[equipslot]) do
			if (not lowestScore or ((ASQDB.Scores[spec][slot]) < lowestScore) ) then
				lowestScore = ASQDB.Scores[spec][slot];
				bestSlot = slot;
			end
		end
		return lowestScore, bestSlot;
	else
		return 0, nil;
	end
end

function aSpeedQuest_ItemScore(stats, subclass, spec, equipslot)
	if not ASQDB.ItemTypes[spec][subclass] and not ASQ_GenericSlots[equipslot] then
		return 0;
	end
	local score = 0;
	for stat, value in pairs(ASQDB.Weights[spec]) do
		if stats[stat] then
			score = score + value * stats[stat];
		end
	end
	return score;
end

function aSpeedQuest_CheckQuestItems()
	local questsCompleted = GetQuestsCompleted();
	local temp = {}; 	--For Quest->Item list
	local temp2 = {}; 	--For PrioItems
	local toRemove = {};
	for key, value in pairs(ASQDB.QuestItems) do
		if not questsCompleted[key] then
			temp[key] = value;
		else
			toRemove[value] = true;
		end
	end
	for key, value in pairs(ASQDB.PrioItems) do
		if not toRemove[key] then
			temp2[key] = value;
		end
	end
	ASQDB.QuestItems = temp;
	ASQDB.PrioItems = temp2;
	print("Cleaned unnecessary quest data");
end

--Mass share related
function aSpeedQuest_StartShare()
	ASQ_NextQuest = {};
	for p = 1, GetNumGroupMembers() do
		ASQ_NextQuest[p] = 1;
		aSpeedQuest_ShareNext(p);
	end
	ASQ_Sharing = true;
end

function aSpeedQuest_ShareNext(pNum)
	while(ASQ_NextQuest[pNum] <= select(1, GetNumQuestLogEntries())) do
		SelectQuestLogEntry(ASQ_NextQuest[pNum]);
		if(GetQuestLogPushable() and not select(5, GetQuestLogTitle(ASQ_NextQuest[pNum]))) then
			if (not IsUnitOnQuest(ASQ_NextQuest[pNum], "party"..pNum)) then
				--print("Sharing", ASQ_NextQuest[pNum]);
				QuestLogPushQuest(ASQ_NextQuest[pNum]);
				ASQ_NextQuest[pNum] = ASQ_NextQuest[pNum] + 1;
				return
			end
		end
		ASQ_NextQuest[pNum] = ASQ_NextQuest[pNum] + 1;
	end
	--print("Exiting loop at",ASQ_NextQuest[pNum]); 
	--	SendAddonMessage(ASQ_Prefix, "StopShare");
	aSpeedQuest_StopSharing(pNum);		
end

function aSpeedQuest_StopSharing(pNum)
	ASQ_NextQuest[pNum] = 999;
	for p = 1, GetNumGroupMembers() do
		if(ASQ_NextQuest[pNum] <= select(1, GetNumQuestLogEntries())) then
			return;
		end
	end
	ASQ_Sharing = false;
	wipe(ASQ_NextQuest);
end

function aSpeedQuest_DoShare(message, name)
	if(message == string.format(ERR_QUEST_PUSH_ACCEPTED_S, name)) then
		return true;
	elseif (message == string.format(ERR_QUEST_PUSH_ONQUEST_S, name)) then
		return true;
	elseif (message == string.format(ERR_QUEST_PUSH_ALREADY_DONE_S, name)) then
		return true;
	elseif (message == string.format(ERR_QUEST_PUSH_INVALID_S, name)) then
		return true;
	elseif (message == ERR_QUEST_PUSH_NOT_ALLOWED_S) then
		return true;
	elseif (message == ERR_QUEST_PUSH_NOT_DAILY_S) then
		return true;
	elseif (message == ERR_QUEST_PUSH_TIMER_EXPIRED_S) then
		return true;
	elseif (message == string.format(ERR_QUEST_PUSH_DIFFERENT_SERVER_DAILY_S, name)) then
		return true;
	else
		return false;
	end
end

function aSpeedQuest_DontShare(message, name)
	if (message == ERR_QUEST_PUSH_NOT_IN_PARTY_S) then
		return true;
	elseif (message == string.format(ERR_QUEST_PUSH_LOG_FULL_S, name)) then
		return true;
	elseif (message == string.format(ERR_QUEST_PUSH_BUSY_S, name)) then
		return true;
	elseif (message == string.format(ERR_QUEST_PUSH_DECLINED_S, name)) then
		return true;
	elseif (message == string.format(ERR_QUEST_PUSH_DEAD_S, name)) then
		return true;
	else
		return false;
	end
end
--]]--

function aSpeedQuest_OnEvent(self, event, ...)
	if (event == "QUEST_ACCEPTED") then
		local questNum = ...;
		QuestLogPushQuest(questNum);
		ASQ_GossipCount = 1
		local itemInfo = GetQuestLogSpecialItemInfo(questNum);
		if itemInfo then		
			local iName = (GetItemInfo((GetQuestLogSpecialItemInfo(questNum))));
			if iName then
				EditMacro(GetMacroIndexByName(ASQ_MacroName), nil, nil, "#showtooltip\n/use "..iName);
			end
		end
		--[[
		local mText = ASQ_QuestMacros[select(9, GetQuestLogTitle(questNum))];
		if mText then
			EditMacro(GetMacroIndexByName(ASQ_MacroName), nil, nil, "#showtooltip\n"..mText);
		end
		--]]--
	
	--[[Mass share related
	elseif	(event == "PARTY_MEMBERS_CHANGED") then
		aSpeedQuest_StartShare();
	]]--
		
	elseif	(event == "QUEST_PROGRESS") then
		if(IsQuestCompletable()) then
			ASQ_GossipCount = 1
			CompleteQuest();
		else
			ASQ_GossipCount = ASQ_GossipCount + 1;
			CloseQuest(); --Returns to gossip screen
		end 
		
	elseif	(event == "QUEST_COMPLETE") then
		local numChoices = GetNumQuestChoices();
		if (numChoices == 0) then
			GetQuestReward(QuestFrameRewardPanel.itemChoice);
		elseif (numChoices == 1) then
			GetQuestReward(1);
		else
			local items = {}
			for i = 1, numChoices do				
				local itemlink = GetQuestItemLink("choice", i);
				items[i] = itemlink;
			end
			local pickIndex = aSpeedQuest_PickItem(items);
			if pickIndex then
				GetQuestReward(pickIndex);
			end
		end
		
	elseif (event == "GOSSIP_SHOW" or event == "QUEST_GREETING") then
		if(GetNumGossipAvailableQuests() >= ASQ_GossipCount) then
			SelectGossipAvailableQuest(ASQ_GossipCount);
		elseif(GetNumGossipActiveQuests() >= ASQ_GossipCount - GetNumGossipAvailableQuests()) then
			SelectGossipActiveQuest(ASQ_GossipCount - GetNumGossipAvailableQuests());
		elseif(GetNumGossipOptions() == 1 and not UnitInRaid("player")) then
			local name = UnitName("target");
			if ASQ_NoDialog[name] then
				return
			end
			SelectGossipOption(1);
			ASQ_GossipCount = 1;
		elseif (ASQ_GossipCount > 1) then
			--CloseGossip(); --Why was this here?
			ASQ_GossipCount = 1;
		end
		
	elseif (event == "QUEST_DETAIL") then
		if(QuestFrame.autoQuest) then
			AcknowledgeAutoAcceptQuest();
		else
			AcceptQuest();
		end
		
	elseif (event == "QUEST_ACCEPT_CONFIRM") then
		ConfirmAcceptQuest();
	--Mass share related
	elseif	(event == "CHAT_MSG_SYSTEM") then
		if(ASQ_Sharing) then
			local message = ...;
			for p=1, GetNumGroupMembers() do
				local name = GetUnitName("party"..p, false);
				if (aSpeedQuest_DoShare(message, name)) then
					aSpeedQuest_ShareNext(p);
				elseif(aSpeedQuest_DontShare(message, name)) then
					aSpeedQuest_StopSharing(p);
				end
			end
		end
	--]]--
	elseif (event == "QUEST_QUERY_COMPLETE") then
		aSpeedQuest_CheckQuestItems();
	
	elseif (event == "ADDON_LOADED" and (select(1, ...)) == "aSpeedQuest") then	
		if not ASQDB or ASQDB.Ver ~= ASQ_CurrentVer then
			aSpeedQuest_Init();
		end
		aSpeedQuest_DoRegs();
		ASQ:UnregisterEvent("ADDON_LOADED");
	end
end